#include "TcpServer.hpp"
#include "Http.hpp"

void Usage(std::string proc)
{
    std::cout << "Usage:\n\t" << proc << " local_port\n"
              << std::endl;
}

std::shared_ptr<HttpResponse> Login(std::shared_ptr<HttpRequest> req)
{
    LOG(DEBUG, "=========================\n");
    std::string userdata;
    if (req->Method() == "GET")
    {
        userdata = req->Args();
    }
    else if (req->Method() == "POST")
    {
        userdata = req->Text();
    }
    else
    {
    }

    // 1. 进程间通信， 比如 pipe！ 还有环境变量！

    // 2. fork();

    // 3. exec(); python / php / java / C++

    // 处理数据了
    LOG(DEBUG, "enter data handler, data is : %s\n", userdata.c_str());


    auto response = Factory::BuildHttpResponose();
    response->AddStatusLine(200, "OK");
    response->AddHeader("Content-Type", "text/html");
    response->AddText("<html><h1>handler data done</h1></html>");
    LOG(DEBUG, "=========================\n");
    return response;
}

// ./httpserver port
int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        Usage(argv[0]);
        return 1;
    }
    uint16_t port = std::stoi(argv[1]);
    HttpServer httpservice;
    // 仿照路径，来进行功能路由！
    httpservice.AddHandler("/login", Login);
    // httpservice.AddHandler("/register", Login);
    // httpservice.AddHandler("/s", Search);

    TcpServer tcpsvr(port, std::bind(&HttpServer::HandlerHttpReqeust, &httpservice, std::placeholders::_1));
    tcpsvr.Loop();

    return 0;
}